<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\model\UserModel;
use app\admin\validate\User;
class Login extends Base
{
    /**
     * 登录页面
     */
    public function index(){
        if(request()->isPost()){
            $username=request()->post('username','','trim');
            $password=request()->post('password','','trim');
            $captcha=request()->post('captcha','','trim');
            if(!captcha_check($captcha)){
                return $this->error('验证码不正确');
            };
            try {
                $this->validate(['name'=>$username,'password'=>$password],'User');
            } catch (\Exception $e) {
                return $this->error($e->getMessage());
            }
            $admin=UserModel::where(['name'=>$username])->find();
            if(empty($admin['password'])){
                return $this->error('账号或者密码错误');
            }
            if($admin['status']==0){
                return $this->error('用户已经被禁用');
            }
            $admin=$admin->toArray();
            if(!password_verifymy($password,$admin['password'])){
                return $this->error('账号或者密码错误');
            }
            unset($admin['password']);
            //登录成功
            session('admin',$admin);
            return $this->success('登录成功',(string)url('index/index'));
        }else{
           return $this->fetch('index/login');
        }

    }
    /**
     * 退出
     */
    public function loginout(){
        session('admin',null);
        $this->success('退出成功',(string)url('login/index'));
    }
}
